package com.example.demo.runner;

import com.example.demo.util.EsUtil;
import com.example.demo.util.RedisUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author MrBird
 * @author FiseTch
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class StartedUpRunner implements ApplicationRunner {
	
	private final ConfigurableApplicationContext context;
	@Resource
	private RedisUtil redisUtil;
//	@Value("${server.port:8080}")
//	private String port;
//	@Value("${server.servlet.context-path:}")
//	private String contextPath;
//	@Value("${spring.profiles.active}")
//	private String active;
	
	@Override
	public void run(ApplicationArguments args) {
		// 测试 Redis连接是否正常
		try {
			redisUtil.set("redis_test", "redis_test");
			if (!redisUtil.hasKey("redis_test")) {
				log.warn("Redis连接异常，请检查Redis连接配置并确保Redis服务已启动");
			} else {
				redisUtil.del("redis_test");
				log.warn("<-------------------------------->");
				log.warn("<---------Redis服务已启动--------->");
				log.warn("<---------Redis服务已启动--------->");
				log.warn("<-------------------------------->");
			}
		} catch (Exception e) {
			log.warn("<------------------------------------------------>");
			log.warn("Redis连接异常，请检查Redis连接配置并确保Redis服务已启动");
			log.warn("Redis连接异常，请检查Redis连接配置并确保Redis服务已启动");
			log.warn("<------------------------------------------------>");
			e.printStackTrace();
		}

		// 测试ES是否连接正常
		try{
			String index = "es_test";
			synchronized (index) {
				if(EsUtil.existsIndex(index)) {
					EsUtil.deleteIndex(index);
				}
				EsUtil.createIndex(index);
				if(EsUtil.existsIndex(index)) {
					EsUtil.deleteIndex(index);
					log.warn("<---------------------------------------->");
					log.warn("<---------ElasticSearch服务已启动--------->");
					log.warn("<---------ElasticSearch服务已启动--------->");
					log.warn("<---------------------------------------->");
				}
			}
		} catch (Exception e) {
			log.warn("<------------------------->");
			log.warn("ElasticSearch连接失败，请检查");
			log.warn("ElasticSearch连接失败，请检查");
			log.warn("<------------------------->");
//			e.printStackTrace();
		}
		
//		if (context.isActive()) {
//			InetAddress address = InetAddress.getLocalHost();
//			String url = String.format("http://%s:%s%s", address.getHostAddress(), port, contextPath);
//			log.info("   __   ____   __  __");
//			log.info("  /  \\ /_  ,','_/ / /");
//			log.info(" / o | ,',' / /_ / /_");
//			log.info("/__,','___/ |__//___");
//			log.info("电子材料平台系统启动完毕，地址：{}", url);
//			log.info("当期前环境为{}", active);
//			log.info("电子材料平台swagger文档，地址：{}/doc.html#/", url);
//		}
	}
}
